from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout,
                             QPushButton, QLabel, QMessageBox)
from PyQt5.QtCore import Qt
import datetime


class PortScanDialog(QDialog):
    def __init__(self, parent=None, port_info=None, scanner=None):
        super().__init__(parent)
        self.port_info = port_info
        self.scanner = scanner
        self.process_pid = port_info.get('process', {}).get(
            'pid') if port_info.get('process') else None

        self.setWindowTitle("端口检测结果")
        self.setMinimumWidth(400)
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout()

        # 创建信息显示区域
        if self.port_info['status'] == 'free':
            info_label = QLabel("检测成功：端口 5000 未被占用")
            layout.addWidget(info_label)

            # 只添加确定按钮
            btn_layout = QHBoxLayout()
            ok_btn = QPushButton("确定")
            ok_btn.clicked.connect(self.accept)
            btn_layout.addWidget(ok_btn)

        else:
            # 显示进程信息
            if self.port_info['process']:
                process = self.port_info['process']
                create_time = datetime.datetime.fromtimestamp(
                    process['create_time']).strftime('%Y-%m-%d %H:%M:%S')

                # 格式化创建时间，如果是 0 则显示"未知"
                create_time_str = (
                    datetime.datetime.fromtimestamp(
                        process['create_time']).strftime('%Y-%m-%d %H:%M:%S')
                    if process['create_time'] != 0 else "未知"
                )

                info_text = f"""
                端口 5000 被占用
                进程信息：
                - PID: {process['pid'] if process['pid'] else '未知'}
                - 名称: {process['name']}
                - 路径: {process['exe']}
                - 状态: {process['status']}
                - 创建时间: {create_time_str}
                - 用户: {process['username']}
                """

                if '权限不足' in process['exe'] or '无法访问' in process['name']:
                    info_text += "\n注意：某些信息无法访问，可能需要管理员权限"
            else:
                info_text = "端口 5000 被占用\n无法获取具体进程信息，可能需要管理员权限运行"

            info_label = QLabel(info_text)
            info_label.setTextFormat(Qt.PlainText)
            layout.addWidget(info_label)

            # 添加按钮
            btn_layout = QHBoxLayout()
            ok_btn = QPushButton("确定")
            release_btn = QPushButton("解除占用")

            ok_btn.clicked.connect(self.accept)
            release_btn.clicked.connect(self.release_port)

            btn_layout.addWidget(ok_btn)
            if self.process_pid:  # 只有在有进程信息时才显示解除占用按钮
                btn_layout.addWidget(release_btn)

        layout.addLayout(btn_layout)
        self.setLayout(layout)

    def release_port(self):
        """解除端口占用"""
        if not self.process_pid or not self.scanner:
            return

        reply = QMessageBox.question(
            self, '确认操作',
            f"确定要终止进程 (PID: {self.process_pid}) 吗？",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            if self.scanner.kill_process(self.process_pid):
                QMessageBox.information(self, "成功", "进程已成功终止")
                self.accept()
            else:
                QMessageBox.warning(
                    self, "错误",
                    "无法终止进程，可能需要管理员权限"
                )
